package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.feigns.admin.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.vo.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    /**
     * 计算热文章
     */
    @Override
    public void computeHotArticle() {
        //1 查询前5天的 （已上架、未删除） 文章数据
        String date = LocalDateTime.now().minusDays(5).format(DateTimeFormatter.ofPattern("yyyy-MM-dd 00:00:00"));
        List<ApArticleConfig> apArticleConfigs = apArticleConfigMapper.selectList(Wrappers.<ApArticleConfig>lambdaQuery()
                .eq(ApArticleConfig::getIsDelete, 0)
                .eq(ApArticleConfig::getIsDown, 0));
        ArrayList<Object> idList = new ArrayList<>();
        for (ApArticleConfig apArticleConfig : apArticleConfigs) {
            Long articleId = apArticleConfig.getArticleId();
            idList.add(articleId);
        }
        List<ApArticle> apArticleList = apArticleMapper.selectList(Wrappers.<ApArticle>lambdaQuery().gt(ApArticle::getPublishTime, date)
                .in(ApArticle::getId, idList));
        //2 计算热点文章分值
        List<HotArticleVo> hotArticleVos = computeArticleScore(apArticleList);
        //3 为每一个频道缓存热点较高的30条文章
        cacheTagToRedis(hotArticleVos);
    }
    @Autowired
    AdminFeign adminFeign;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private void cacheTagToRedis(List<HotArticleVo> hotArticleVos) {
        ResponseResult responseResult = adminFeign.selectAllChannel();
        if (responseResult.getCode() == 0) {
            List<AdChannel> list = JSON.parseArray(JSON.toJSONString(responseResult.getData()), AdChannel.class);
            //2 遍历频道列表，筛选当前频道下的文章
            for (AdChannel channel : list) {
                List<HotArticleVo> channelArticles = hotArticleVos.stream().filter(hotArticle ->
                        hotArticle.getChannelId().equals(channel.getId())
                ).collect(Collectors.toList());
                sortAndCache(channelArticles, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + channel.getId());
            }
        }
        //4 给推荐频道缓存30条数据  所有文章排序之后的前30条
        sortAndCache(hotArticleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }
    /**
     * 缓存热点文章
     * @param hotArticleVos
     * @param cacheKey
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String cacheKey) {
        // 对文章进行排序
        hotArticleVos = hotArticleVos.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30)
                .collect(Collectors.toList());
        redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(hotArticleVos));
    }

    /**
     * 2 计算热点文章的分值
     * @param apArticleList
     * @return
     */
    private List<HotArticleVo> computeArticleScore(List<ApArticle> apArticleList) {
// 定义返回集合
        return apArticleList.stream().map(apArticle -> {
            HotArticleVo hotArticleVo = new HotArticleVo(apArticle);
            // 2.1计算文章分值算法
            Integer score = computeScore(apArticle);
            hotArticleVo.setScore(score);
            return hotArticleVo;
        }).collect(Collectors.toList());
    }
    /**
     * 2.1计算文章分值算法
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        int score = 0;
        // 阅读 1
        if (apArticle.getViews() != null) {
            score += apArticle.getViews() * ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }
        // 点赞 3
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        // 评论 5
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        // 收藏 8
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}

